package com.atguigu.tingshu.common.annotation;

import com.alibaba.nacos.client.naming.remote.gprc.redo.data.RedoData;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

//切面类练习
@Aspect
//@Component
public class GuiguLoginAspect2 {


    @Autowired
    private RedisTemplate redisTemplate;


    @SneakyThrows
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(guiGuLogin)")
    public Object GuiguLoginAspect(ProceedingJoinPoint joinPoint, GuiGuLogin guiGuLogin){
        //获取request对象
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("token");
        if(guiGuLogin.required()){
            //表示必须登录
            if(StringUtils.isEmpty(token)){
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
            UserInfo userInfo =(UserInfo) redisTemplate.opsForValue().get(token);
           if(userInfo==null){
               throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
           }
        }
        if(!StringUtils.isEmpty(token)){
            UserInfo userInfo =(UserInfo) redisTemplate.opsForValue().get(token);
            if(userInfo!=null){
                Long userInfoId = userInfo.getId();
                AuthContextHolder.setUserId(userInfoId);
            }
        }
        Object proceed = joinPoint.proceed();
        return proceed;
    }
}
